package cn.iocoder.yudao.module.trade.job.algorithm;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.module.trade.job.algorithm.Constant.*;

@Service
@Slf4j
public class AlgorithmService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /***
     * 登陆
     * @return
     */
    private String login() {
        String token = Convert.toStr(redisTemplate.opsForValue().get(ALGORITHM_LOGIN));
        if (StrUtil.isEmpty(token)) {
            refresh();
            return login();

        }
        return token;
    }

    /***
     * 刷新token
     */
    private void refresh() {
        Map<String, Object> ps = MapUtil.newHashMap();
        ps.put("username", Constant.USERNAME);
        ps.put("password", Constant.PASSWORD);
        String resToken = HttpUtil.post(LOGIN, ps);
        log.info("算法登陆结果[resToken]:{}", resToken);
        if (StrUtil.isEmpty(resToken)) {
            log.error("算法登陆异常");
        }
        JSONObject jsonObject = JSONObject.parseObject(resToken);
        String token = jsonObject.getString("token");
        redisTemplate.opsForValue().set(ALGORITHM_LOGIN, token, jsonObject.getLongValue("expires_in"));
    }

    /***
     * 计算运营轮次
     * @param reqList
     */
    public JSONObject calculateRound(List<CalculateRoundReq> reqList) {
        HttpRequest request = HttpUtil.createPost(CALCULATE_ROUND);
        request.header("Authorization", login());
        request.body(JSONObject.toJSONString(reqList));
        HttpResponse response = request.execute();
        log.info("计算运营轮次:{}", JSONObject.toJSONString(response));
        return JSONObject.parseObject(response.body());
    }

    /***
     * 计算多期返利
     * @param reqList
     * @return
     */
    public JSONObject getAllRebate(GetAllRebateReq reqList) {
        HttpRequest request = HttpUtil.createPost(GET_ALL_REBATE);
        request.header("Authorization", login());
        request.body(JSONObject.toJSONString(reqList));
        HttpResponse response = request.execute();
        log.info("计算运营轮次:{}", JSONObject.toJSONString(response));
        return JSONObject.parseObject(response.body());
    }
}
